<?php

namespace app\modules\album\controllers;

use Yii;
use yii\web\Controller;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\data\Pagination;

use common\tools\HttpTool;
use common\tools\WeChatTool;
use common\models\AlbumAppModel;
use common\models\AlbumAppItemModel;
use common\models\AlbumTemplateModel;
use common\models\AlbumTemplateClassModel;
use common\models\AlbumMusicClassModel;
use editors\Uploader;
use app\modules\album\models\AlbumCollectModel;
/**
 * Default controller for the `album` module
 */
class AppController extends Controller
{
    public $title;
    public $keywords;
    public $description;
    
    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
//                'only' => ['create', 'docreate','templateajax','changetemplate','dochange'],
                'rules' => [
//                    // deny all POST requests
//                    [
//                        'allow' => false,
//                        'verbs' => ['POST']
//                    ],
                    // allow authenticated users
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    // everything else is denied
                ],
            ],
        ];
    }
    /**
    * @inheritdoc
    */
    public function actions()
    {
        return [                    
            'upload' => [
                'class' => 'editors\UEditorAction',
            ]
        ];
    }
    /**
     * 我的相册
     * @return string
     */
    public function actionIndex()
    {
        $this->title = '';
        $this->keywords = '';
        $this->description = '';
        
        $model = new AlbumAppModel();
        $data = $model->find() 
            ->where(['<>','is_delete',1])
            ->andWhere(['=','uid', \yii::$app->user->identity->id] ) 
            ->orderBy(['updated_at'=> SORT_DESC,]);        
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => 8]);
        $albums = $data->offset($pages->offset)->limit($pages->limit)->all();   
        
        $cmodel = new AlbumCollectModel();  
        $cdata = $cmodel->find() 
            ->where(['=','uid', \yii::$app->user->identity->id] ) 
            ->orderBy(['updated_at'=> SORT_DESC,]);        
//        $cpages = new Pagination(['totalCount' =>$cdata->count(), 'pageSize' => 8]);
        $calbums = $cdata->all();  
        return $this->render('index',[
            "albums"=>$albums, 
            'pages' => $pages,
            "calbums"=>$calbums, 
            'user'=>\yii::$app->user->identity]);
    }
    /**
     * 相册广场
     * @return string
     */
    public function actionGallery()
    {
        $this->title = '相册广场';
        $this->keywords = '相册广场';
        $this->description = '相册广场';
        
        $model = new AlbumAppModel();
        $data = $model->find() 
            ->where(['<>','is_delete',1])
            ->andWhere(['=','status', 2] ) 
            ->orderBy(['updated_at'=> SORT_DESC,]);        
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => 8]);
        $albums = $data->offset($pages->offset)->limit($pages->limit)->all();   
        return $this->render('gallery',["albums"=>$albums, 'pages' => $pages,'user'=>\yii::$app->user->identity]);
    }
    
    public function actionCreate()
    {
        return $this->render('create');
    }  
    public function actionChangepic($aid)
    {
        $album = AlbumAppModel::findOneById($aid);
        $pics  = $album->items;      
        return $this->render('update',['aid'=>$aid,'pics'=>$pics,"album"=>$album]);
    }  
    /**
     * 创建相册
     * @return type
     */
    public function actionDocreate()           
    {
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $post = Yii::$app->request->post();     
        if(!isset($post["pics"])){
            throw new BadRequestHttpException("必要参数丢失！");
        }
     
        $pics       = $post["pics"];
        $userId     = yii::$app->user->identity->id;
        $userOpenid = yii::$app->user->identity->openid;
        $userName   = yii::$app->user->identity->wx_username;
        
        $albumAppModel             = new AlbumAppModel();
        $albumAppModel->uid        = $userId;
        $albumAppModel->openid     = $userOpenid;
        $albumAppModel->status     = 0;//默认私有
        $albumAppModel->title      = $userName."的相册";
        $albumAppModel->is_delete  = 0;
        $albumAppModel->pic        = $post["pics"][0];
        $albumAppModel->template   = \Yii::$app->params["weixinConf"]["template"];
        $albumAppModel->music   = \Yii::$app->params["weixinConf"]["music"];
        
        
        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();  //开启事务
        try {                     
            if($albumAppModel->save())  
             {  
                foreach ($pics as $pic){
                    $albumAppItemModel         = new AlbumAppItemModel();
                    $albumAppItemModel->app_id = $albumAppModel->id;
                    $albumAppItemModel->openid = $albumAppModel->openid;
                    $albumAppItemModel->pic    = $pic;
                    if(!$albumAppItemModel->save()){
                         $error=array_values($albumAppItemModel->getFirstErrors())[0];
                         throw new Exception($error);//抛出异常
                     }
                }
               

             }else{
                $error=array_values($albumAppModel->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
             }  
            // 提交记录(执行事务)
            $transaction->commit();           
            return [
                'message' => "创建相册成功",
                'code' => 1,
                'aid' => $albumAppModel->id,
            ];    
        } catch (Exception $e) {   
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            return [
                'message' => "创建相册失败",
                'code' => 0,
            ];     
        }                                
    }   
    /**
     * 创建相册(微信上传图片)
     * @return type
     */
    public function actionDowechatcreate()           
    {
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $post = Yii::$app->request->post();     
        if(!isset($post["pics"])){
            throw new BadRequestHttpException("必要参数丢失！");
        }
        //图片上传配置
        $config = array(
            "pathFormat" => "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
            "maxSize" =>  2048000,
            "allowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
            "oriName" => "remote.png"
        );    
        
        $pics       = $post["pics"];
        $userId     = yii::$app->user->identity->id;
        $userOpenid = yii::$app->user->identity->openid;
        $userName   = yii::$app->user->identity->wx_username;
        
        $albumAppModel             = new AlbumAppModel();
        $albumAppModel->uid        = $userId;
        $albumAppModel->openid     = $userOpenid;
        $albumAppModel->status     = 0;//默认私有
        $albumAppModel->title      = $userName."的相册";
        $albumAppModel->is_delete  = 0;
        $albumAppModel->pic        = $post["pics"][0];
        $albumAppModel->template   = \Yii::$app->params["weixinConf"]["template"];
        $albumAppModel->music   = \Yii::$app->params["weixinConf"]["music"];
        
        
        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();  //开启事务
        try {                     
            if($albumAppModel->save())  
             {  
                foreach ($pics as $pic){
                    $imageurl = WeChatTool::getImageMedia($pic);    
                    $item = new Uploader($imageurl, $config, "remote");
                    $info = $item->getFileInfo();
                    if(isset($info["url"])){
                        $albumAppItemModel         = new AlbumAppItemModel();
                        $albumAppItemModel->app_id = $albumAppModel->id;
                        $albumAppItemModel->openid = $albumAppModel->openid;
                        $albumAppItemModel->pic    = $info["url"];
                        if(!$albumAppItemModel->save()){
                             $error=array_values($albumAppItemModel->getFirstErrors())[0];
                             throw new Exception($error);//抛出异常
                         }
                    }else{
                        throw new Exception("获取微信图片失败");//抛出异常
                    }                 
                }             
             }else{
                $error=array_values($albumAppModel->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
             }  
            // 提交记录(执行事务)
            $transaction->commit();           
            return [
                'message' => "创建相册成功",
                'code' => 1,
                'aid' => $albumAppModel->id,
            ];    
        } catch (Exception $e) {   
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            return [
                'message' => "创建相册失败",
                'code' => 0,
            ];     
        }                                
    }   
    /**
     * 更新相册
     * @return type
     */
    public function actionDoupdate()           
    {
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $post = Yii::$app->request->post();     
        if(!isset($post["pics"])||!isset($post["aid"])){
            throw new BadRequestHttpException("必要参数丢失！");
        }
     
        $pics       = $post["pics"];
        $aid        = $post["aid"];      
        
        $albumAppModel             = AlbumAppModel::findOneById($aid);
                    
        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();  //开启事务
        try {                     
            foreach ($pics as $pic){
                $albumAppItemModel         = new AlbumAppItemModel();
                $albumAppItemModel->app_id = $albumAppModel->id;
                $albumAppItemModel->openid = $albumAppModel->openid;
                $albumAppItemModel->pic    = $pic;
                if(!$albumAppItemModel->save()){
                     $error=array_values($albumAppItemModel->getFirstErrors())[0];
                     throw new Exception($error);//抛出异常
                 }
            }
            // 提交记录(执行事务)
            $transaction->commit();           
            return [
                'message' => "编辑相册成功",
                'code' => 1,
                'aid' => $albumAppModel->id,
            ];    
        } catch (Exception $e) {   
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            return [
                'message' => "编辑相册失败",
                'code' => 0,
            ];     
        }                                
    }   
    /**
     * 更新相册
     * @return type
     */
    public function actionDelpic()           
    {
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $post = Yii::$app->request->post();     
        if(!isset($post["id"])){
            throw new BadRequestHttpException("必要参数丢失！");
        }
     
        $id  = $post["id"];      
        
        $albumAppItem  = AlbumAppItemModel::findOneById($id);  
        $albumApp      = AlbumAppModel::findOneById($albumAppItem->app_id);  
        if($albumApp->pic==$albumAppItem->pic){
             foreach ($albumApp->items as $item){
                 if($item["id"]!==$albumAppItem->id){
                     $albumApp->pic = $item["pic"];
                     $albumApp->save();
                 }
             }
         }
        if($this->delPic($albumAppItem->pic)){       
            $albumAppItem->delete();
            return [
                'message' => "照片删除成功",
                'code' => 1,
            ];    
        }
        $albumApp->pic = $albumAppItem->pic;
        return [
                'message' => "照片删除失败",
                'code' => 0,
        ];                             
    }   
    public function actionSettpic()           
    {
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $post = Yii::$app->request->post();     
        if(!isset($post["id"])||!isset($post["aid"])){
            throw new BadRequestHttpException("必要参数丢失！");
        }
     
        $id  = $post["id"];      
        $aid  = $post["aid"];      
        
        $albumApp      = AlbumAppModel::findOneById($aid);  
        $albumAppItem  = AlbumAppItemModel::findOneById($id);  
        $albumApp->pic = $albumAppItem->pic;
        if($albumApp->save()){ 
            return [
                'message' => "封面设置成功",
                'code' => 1,
            ];    
        }
        return [
                'message' => "封面设置失败",
                'code' => 0,
        ];                             
    }   
     /**
     * 模板
     * @return type
     */
    public function actionTemplateajax(){
        
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;  
        $post = Yii::$app->request->post();     
        if(!isset($post["classid"])){
            throw new BadRequestHttpException("必要参数丢失！");
        }
        $classid=$post["classid"];
        if($classid==0){
            $model     = new AlbumTemplateModel();
//            $templates  = $model->find()->where(['is_good'=>"1"])->all();
            $templates  = $model->find()->all();
        }else{
            $model     = new AlbumTemplateClassModel();
            $templates = $model->findOneById($classid)->items;
        }
        return [
            'code' => 1,
            'templates' => $templates,
        ];         
    }
     /**
     * 默认推荐模板
     * 
     */
    public function actionChangetemplate($aid){
        $this->title = '选择模板';
        $this->keywords = '选择模板';
        $this->description = '选择模板';
        $model      = new AlbumTemplateModel();
//        $templates  = $model->find()->where(['is_good'=>"1"])->all();
        $templates  = $model->find()->all();
        $classModel = new AlbumTemplateClassModel();
        $class      = $classModel->find()->orderBy(['sort'=>SORT_DESC])->all();
        return $this->render('changeTemplate',["templates"=>$templates,"aid"=>$aid,'class'=>$class]);
        
    }
     /**
     * 编辑相册
     * @return type
     */
    public function actionDochange($type="template"){
        
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;  
        
        $post     = Yii::$app->request->post();   
        $model    = new AlbumAppModel();
            
        if(!isset($post["aid"])){
            throw new BadRequestHttpException("必要参数{相册id}丢失！");
        } 
        $aid      = $post["aid"];
        $albumApp = $model->findOneById($aid);        
        if(empty($albumApp)){
            throw new NotFoundHttpException("相册不存在");
        }     
        if($albumApp->uid != yii::$app->user->identity->id){
            throw new ForbiddenHttpException("你没有权限编辑该相册！");
        }
             
        if($type=='music'){
            if(!isset($post["music"])){
                throw new BadRequestHttpException("必要参数丢失！");
            }
            $music           = $post["music"]; 
            $albumApp->music = $music;
        }else{
            if(!isset($post["template"])||!isset($post["changeMusic"])){
                throw new BadRequestHttpException("必要参数丢失！");
            }           
            $changeMusic  = $post["changeMusic"]; 
            if($changeMusic){
                $template = AlbumTemplateModel::findOneById($post["template"]); 
                if($template){
                    $albumApp->template = $template->dir;
                    $albumApp->music    = $template->music;
                }else{
                    throw new Exception("模板不存在！");//抛出异常
                }
                
            } else {
                $albumApp->template = $post["template"];
            }                      
        }
                      
        if($albumApp->save()){
            return [
                'code' => 1,
                'aid' => $aid,
                'message' => "成功",
            ];   
        }
        $error=array_values($albumApp->getFirstErrors())[0];
        throw new Exception($error);//抛出异常
        return [
                'code' => 0,
                'message' => "失败",
        ];   
                  
    }
    /**
     * 音乐选择
     * 
     */
    public function actionChangemusic($aid){
              
        $model      = new AlbumMusicClassModel();
        $class  = $model->find()->all();
        return $this->render('changeMusic',["class"=>$class,'aid'=>$aid]);
        
    }
    /**
     * 音乐选择
     * 
     */
    public function actionGetmusic(){
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;  
        
        $post = Yii::$app->request->post();  
        if(!isset($post["key"])){
            throw new BadRequestHttpException("必要参数丢失！");
        }
        $pageSize   = \Yii::$app->params["weixinConf"]["qqMusicPageSize"];   
        $qqMusicUrl = \Yii::$app->params["weixinConf"]["qqMusicUrl"].$pageSize."&w={$post["key"]}";
        $data = HttpTool::http_get($qqMusicUrl);
//        echo $qqMusicUrl;
        $data = ltrim(rtrim($data,")"),"MusicJsonCallback(");
//        return $data;
        $titleArr = array();
        $musicObject = json_decode($data);
        $list = $musicObject->list;
        $musicData = array_filter($list,function($mObject)use(&$titleArr){
            if(in_array($mObject->songname, $titleArr)){
                return false;
            }else{
                array_push($titleArr, $mObject->songname);
                return true;
            }
        });
        $musicObject->list = $musicData;
        return $musicObject;            
    }
    /**
     * 音乐选择
     * 
     */
    public function actionChangetitle($aid){
        
        $model = AlbumAppModel::findOneById($aid);  
        if(empty($model)){
            throw new NotFoundHttpException("相册不存在");
        }
        if($model->uid != yii::$app->user->identity->id){
            throw new ForbiddenHttpException("你没有权限编辑该相册！");
        }
        if ($model->load(Yii::$app->request->post())&&$model->validate()) {
            $model->save();
//            echo "<pre>";
//            print_r($model);die;
            return $this->redirect(["/album/".$aid]);
        }else{
            return $this->render('changetitle',['model'=>$model]);
        }                  
    }
     /***
     * 删除相册
     */
    public function actionDelete(){
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;  
        
        $post = Yii::$app->request->post();  
        if(!isset($post["aid"])){
            throw new BadRequestHttpException("必要参数丢失！");
        }
        
        $model = AlbumAppModel::findOneById($post["aid"]); 
        if($model->uid != yii::$app->user->identity->id){
            throw new ForbiddenHttpException("该相册不属于你！");
        }
        $items = $model->items;
 
        if($model->delete()){
            foreach ($items as $item){
                $this->delPic($item['pic']);
            }
            return [
                'code' => 1,
                'aid' => $post["aid"],
                'message' => "相册删除成功",
            ];  
        } 
        return [
                'code' => 0,
                'aid' => $post["aid"],
                'message' => "相册删除失败",
            ];  
    }
    public function actionZan(){
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;  
        
        $post = Yii::$app->request->post();  
        if(!isset($post["aid"])){
            throw new BadRequestHttpException("必要参数丢失！");
        }
        
        $model = AlbumAppModel::findOneById($post["aid"]); 
        if($model->uid == yii::$app->user->identity->id){
            return [
                'code' => 0,
                'message' => "亲，不能给自己点赞哦！",
            ];  
        }
        
        if($model->incrementZan()){          
            return [
                'code' => 1,
                'message' => "点赞成功",
            ];  
        } 
        return [
                'code' => 0,
                'message' => "点赞失败",
            ];  
    }
    public function actionCollect(){
        if (!Yii::$app->request->isAjax){
            throw new BadRequestHttpException("非法请求！");
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;  
        
        $post = Yii::$app->request->post();  
        if(!isset($post["aid"])){
            throw new BadRequestHttpException("必要参数丢失！");
        }
        
        
        $app = AlbumAppModel::findOneById($post["aid"]); 
        if($app->uid == \yii::$app->user->identity->id){
            return [
                'code' => 0,
                'message' => "亲，不能收藏自己的相册哦！",
            ];  
        }
        $id = \yii::$app->user->identity->id."/".$post["aid"];
        $model = AlbumCollectModel::findOneById($id);
        if($model){
            if($model->delete()){
                return [
                    'code' => 1,
                    'message' => "取消收藏成功！",
                ];  
            }
            return [
                    'code' => 0,
                    'message' => "取消收藏失败",
                ];  
        }
        
        $model = new AlbumCollectModel();
        $model->id = $id;
        $model->uid = \yii::$app->user->identity->id;
        $model->aid = $post["aid"];
        
        if($model->save()){          
            return [
                'code' => 1,
                'message' => "收藏成功",
            ];  
        }    
        return [
                'code' => 0,
                'message' => "收藏失败",
            ];  
    }
    /**
     * 删除相册下照片
     */
    private function delPic($pic){
        try { 
            $rootPath = \Yii::getAlias('@frontend/web');    
            $pic = $rootPath.$pic; 
            if(file_exists($pic))
            unlink($pic);
            return true;
        } catch (Exception $e) {   
            return false;  
        }          
    }
}
